<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\model\Agreement;
use app\common\model\Banner;
use app\common\model\Category;
use app\common\model\InformationQualifications;
use app\common\model\MembershipCard;
use app\common\model\UserQualifications;
use think\Exception;

class Common extends Api
{
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = ["*"];

    protected $params = [];

    public function __construct()
    {
        parent::__construct();
        $this->params = array_filter(array_merge($this->request->post(), $this->request->get()));
    }

    /**
     * 获取banner布局位置类型
     * */
    public function getBannerPositionType()
    {
        try {
            $array = [];
            if (!empty(config('site.bannerPositionType'))) {
                foreach (config('site.bannerPositionType') as $key => $value) {
                    $array[$key]['id'] = $key;
                    $array[$key]['value'] = $value;
                }
            }
            $this->success('success', array_values($array));
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取banner
     * */
    public function getBanner()
    {
        try {
            $validate = $this->validate($this->params, 'app\\api\\validate\\Common.getBanner');
            if ($validate !== true) {
                throw new Exception($validate);
            }
            $bannerList = Banner::field('id, path, position_type, type, url')->where(['position_type' => $this->params['position_type']])->select();
            $this->success('success', $bannerList);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取协议类型
     * */
    public function getAgreementType()
    {
        try {
            $array = [];
            if (!empty(config('site.agreement'))) {
                foreach (config('site.agreement') as $key => $value) {
                    $array[$key]['id'] = $key;
                    $array[$key]['value'] = $value;
                }
            }
            $this->success('success', array_values($array));
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取协议
     * */
    public function getAgreement()
    {
        try {
            $validate = $this->validate($this->params, 'app\\api\\validate\\Common.getAgreement');
            if ($validate !== true) {
                throw new Exception($validate);
            }
            $field = 'id, type, content, title';
            if (!$agreement = Agreement::field($field)->where(['type' => $this->params['agreement_type']])->find()) {
                throw new Exception('不存在此协议');
            }
            $this->success('success', $agreement);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取百度AccessToken
     * */
    public function getBaiDuAccessToken()
    {
        try {
            $validate = $this->validate($this->params, 'app\\api\\validate\\Common.getBaiDuAccessToken');
            if ($validate !== true) {
                throw new Exception($validate);
            }

            $url = 'https://aip.baidubce.com/oauth/2.0/token';
            $array = array(
                'client_id' => config('site.' . $this->params['keyName'])['apiKey'],
                'client_secret' => config('site.' . $this->params['keyName'])['apiSecretKey'],
                'grant_type' => 'client_credentials'
            );
            $response = http_query_url($url . '?' . http_build_query($array), 'post', array(), array(
                'Content-Type: application/json',
                'Accept: application/json'
            ));
            $this->success('success', $response);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取课程 & 课程 & 行业分类
     * */
    public function getCateList()
    {
        try {
            $validate = $this->validate($this->params, 'app\\api\\validate\\Common.getCateList');
            if ($validate !== true) {
                throw new Exception($validate);
            }
            $condition['type'] = $this->params['cateType'];
            if (!empty($this->params['searchName'])) {
                $condition['pid'] = ['<>', 0];
                $searchName = mb_str_split($this->params['searchName'], 1);
                $searchName = '%' . implode('%', $searchName) . '%';
                $condition['name|nickname'] = ['LIKE', $searchName];
            }
            $list = collection(Category::instance()->where($condition)->select())->toArray();

            if (!empty($this->params['searchName'])) {
                foreach ($list as &$value) {
                    // 使用 preg_replace 高亮关键词
                    $value['highlightedName'] = preg_replace(
                        '/(' . preg_quote($this->params['searchName'], '/') . ')/i',
                        '<span class="highlight">$1</span>',
                        $value['name']
                    );
                }
            }
            if (empty($this->params['searchName'])) {
                $list = buildTree($list);
            }
            $this->success('success', $list);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取会员套餐
     * */
    public function getMemberCard()
    {
        try {
            $result = collection(MembershipCard::instance()
                ->field('id, type, month, name, original_price, sales_price, content')
                ->order('month ASC')
                ->select())
                ->toArray();
            $list = [];
            foreach ($result as &$value) {
                $list[$value['type']]['name'] = ($value['type'] == 1) ? '豪华会员' : 'SVIP会员';
                $list[$value['type']]['type'] = $value['type'];
                $list[$value['type']]['list'][] = $value;
            }
            $this->success('success', array_values($list));
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取后台配置
     * */
    public function getCommonConfig()
    {
        if (empty($this->params['keyName'])) {
            $this->error('缺少配置的KEY');
        }
        $this->success('success', config('site.' . $this->params['keyName']));
    }

    /**
     * 获取资质详情
     * */
    public function getQualificationsDetail()
    {
        if (empty($this->params['id'])) {
            $this->error("缺少资质id");
        }

        if (!$qualifications = UserQualifications::instance()->get(['id' => $this->params['id']])) {
            $this->error("该资质不存在");
        }

        $this->success('success', $qualifications);
    }


    /**
     * 获取线下资料资质详情
     * */
    public function getInformationQualificationsDetail()
    {
        if (empty($this->params['id'])) {
            $this->error("缺少资质id");
        }

        if (!$qualifications = InformationQualifications::instance()->get(['id' => $this->params['id']])) {
            $this->error("该资质不存在");
        }

        $this->success('success', $qualifications);
    }
}